﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;
using System.IO;
using Framework;

namespace FrameworkEditor
{
    [CustomEditor(typeof(SpriteSet))]
    //SpriteSet添加多选标签
    [UnityEditor.CanEditMultipleObjects]
    public class SpriteSetInspector : Editor
    {
        public override void OnInspectorGUI()
        {
            base.OnInspectorGUI();
            GUILayout.Space(10);
            if (GUILayout.Button("Refresh"))
            { 
                Refresh();
            }

            if (GUI.changed)
            {
                EditorUtility.SetDirty(target);
            }
            serializedObject.ApplyModifiedProperties();    
        }

        private const string spriteSetName = "spriteset";
        private void Refresh()
        {
            var asset = serializedObject.targetObject as SpriteSet;
            var dirPath = AssetDatabase.GetAssetPath(asset.folder);
            asset.contentSet = new List<Sprite>();

            if(!_IsValiedAtlasDir(dirPath))
            { 
                EditorUtility.DisplayDialog("刷新SpriteSet", "请确保引用的图集文件夹路径是合法的! ", "确定");
                return;
            }
            
            foreach(var item in Directory.GetFiles(dirPath, "*.png"))
            {
                Sprite sprite = AssetDatabase.LoadAssetAtPath<Sprite>(item);
                asset.contentSet.Add(sprite);
            }
            EditorUtility.SetDirty(asset);
            AssetDatabase.SaveAssets();
            AssetDatabase.Refresh();   
        }

        private bool _IsValiedAtlasDir(string dirName)
        {
            return !string.IsNullOrEmpty(dirName) && dirName.IndexOf(spriteSetName) != -1;
        }
    }
}
